package org.example.shoppingsystem.controller;

import org.example.shoppingsystem.model.User;
import org.example.shoppingsystem.service.UserService;
import org.example.shoppingsystem.service.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.SQLException;

@Controller
public class RegisterController {
    private UserService userService = new UserServiceImpl();

    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    @PostMapping("/register")
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("account") String account,
                           Model model) {
        String errMsg = "";
//        创建user对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAccount(account);

        try {
            if (userService.register(user)) {
                return "login"; // 注册成功，跳转到登录页面
            } else {
                errMsg += "账号已存在，请选择其他账号。";
            }
        } catch (SQLException e) {
            errMsg += "数据库操作出错，请稍后再试。";
            e.printStackTrace();
        }

        if (!errMsg.isEmpty()) {
            model.addAttribute("err", errMsg);
            return "register"; // 注册失败，返回注册页面
        }
        return "register";
    }
}